import os
from typing import List
from dataclasses import dataclass
import joblib
import numpy as np


@dataclass
class RemoteFilePredictAddRequest:
    # 用户 id
    userId: int
    # 文件 id
    fileId: int
    # 训练 id
    trainId: int
    # 采用模型
    model: str
    # 传入参数
    params: List[float]


@dataclass
class FilePredictResult:
    # 编号
    code: int
    # 数据
    data: int
    # 信息
    message: str


class doFilePredictExecute:

    def doFilePredict(self, remoteFilePredictAddRequest: RemoteFilePredictAddRequest):
        userId = remoteFilePredictAddRequest.userId
        fileId = remoteFilePredictAddRequest.fileId
        trainId = remoteFilePredictAddRequest.trainId
        modelName = remoteFilePredictAddRequest.model
        params = remoteFilePredictAddRequest.params

        # 构造路径找到存储模型
        global_file_dir_name = "train"
        global_user_path_name = global_file_dir_name + "/" + "user-" + str(userId)
        global_file_path_name = global_user_path_name + "/" + "file-" + str(fileId)
        global_train_path_name = global_file_path_name + "/" + modelName + "-" + str(trainId)

        print(global_train_path_name)

        try:

            model = joblib.load(global_train_path_name + "/" +"model.joblib")
            scaler = joblib.load(global_train_path_name + "/" +"scaler.joblib")

        except FileNotFoundError:
            return FilePredictResult(40000, 0.0, "模型未创建")

        predict_data = np.array([params])
        # 对新数据进行缩放
        scaled_data = scaler.transform(predict_data)

        print(scaled_data)

        # 使用模型进行预测
        predictions = model.predict(scaled_data)

        return FilePredictResult(0, int(predictions[0]), "ok")


if __name__ == '__main__':
    remoteFilePredictAddRequest = RemoteFilePredictAddRequest(
        userId=1884211650339426305,
        fileId=1887752739488174081,
        model="KNN",
        trainId=1888448488645050369,
        params=[7.50e+01, 1.00e+00, 2.46e+02, 0.00e+00, 1.50e+01, 0.00e+00, 1.27e+05, 1.20e+00, 1.37e+02, 1.00e+00, 0.00e+00, 1.00e+01]
    )
    print(doFilePredictExecute().doFilePredict(remoteFilePredictAddRequest))
